<?php

namespace app\common\model\user;

use app\common\model\DiamondLog;
use app\common\model\GoldLog;
use app\common\model\User;
use think\Model;


class Withdraw extends Model
{

    // 表名
    protected $table = 'user_withdraw';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [];

    public static function init()
    {
        self::afterUpdate(function ($row) {
            $origin = $row->getOriginData();
            if ($origin['status'] == 0 && $row['status'] == 2) {
                $user = User::find($row->user_id);
                if ($user) {
                    switch ($row['type']) {
                        case 1:
                            $log = new GoldLog();
                            $name = 'gold';
                            break;
                        case 2:
                            $log = new DiamondLog();
                            $name = 'diamond';
                            break;
                    }

                    $before = $user[$name];
                    $after = function_exists('bcadd') ? bcadd($user[$name], $row['num'], 2) : $user[$name] - $row['num'];
                    $log_id = $log->insertGetId([
                        'user_id' => $user['id'], $name => $row['num'],
                        'before' => $before, 'after' => $after,
                        'memo' => "提现失败,返还", 'type' => 3,
                        'createtime' => time()
                    ]);
                    $user->save([$name => $after]);
                    self::where('id', $row['id'])->update(['log_rn_id' => $log_id]);
                }
            }
        });
    }

    public function getOriginData()
    {
        return $this->origin;
    }

    public function getTypeList()
    {
        return [1 => '金币', 2 => '钻石'];
    }

    public function getStatusList()
    {
        return [0 => '申请中', 1 => '已打款', 2 => '已拒绝'];
    }

    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
